package xyz.icxl.kotlion.ext.binding

import android.animation.ObjectAnimator
import android.view.View
import androidx.core.animation.doOnEnd
import androidx.databinding.BindingAdapter
import xyz.icxl.kotlion.ext.view.selfClickListener
import java.time.Duration

/**
 * 设置View显示([View.VISIBLE])隐藏([View.GONE])状态
 */
@BindingAdapter("ext_VisibilityOrGone")
fun View.visibilityOrGone(isVisibility: Boolean?) {
    visibility = if (isVisibility == true) View.VISIBLE else View.GONE
}

/**
 * 设置View显示([View.VISIBLE])隐藏([View.INVISIBLE])状态
 */
@BindingAdapter("ext_VisibilityOrInvisible")
fun View.visibilityOrInvisible(isVisibility: Boolean?) {
    visibility = if (isVisibility == true) View.VISIBLE else View.INVISIBLE
}

@BindingAdapter("ext_selfClick")
fun View.selfClick(l: () -> Unit) {
    selfClickListener { l() }
}

/**
 * 显示一个View 带动画效果
 */
fun View.fadeToVisible(duration: Long = 180) {
    if (visibility == View.GONE) {
        visibility = View.VISIBLE
        ObjectAnimator.ofFloat(this, "alpha", 0f, 1f).setDuration(duration).start()
    }
}

/**
 * 隐藏一个View 带动画效果
 */
fun View.fadeToGone(duration: Long = 180) {
    if (visibility == View.VISIBLE) {
        ObjectAnimator
            .ofFloat(this, "alpha", 1F, 0f).apply {
                doOnEnd {
                    visibility = View.GONE
                }
            }
            .setDuration(duration)
            .start()
    }
}